// MyChatComponent.jsx
import React, { useEffect, useState } from 'react';
import * as signalR from '@microsoft/signalr';

const MyChatComponent = () => {
  const [connection, setConnection] = useState(null);
  const [messages, setMessages] = useState([]);
  const [newMessage, setNewMessage] = useState('');

  useEffect(() => {
    // 创建 SignalR 连接
    const newConnection = new signalR.HubConnectionBuilder()
      .withUrl('http://localhost:5127/todoHub') // 指定 SignalR Hub 的 URL
      .configureLogging(signalR.LogLevel.Information)
      .build();

    setConnection(newConnection);

    // 启动连接
    newConnection.start()
      .then(() => console.log('Connection started!'))
      .catch(err => console.error('Error while establishing connection:', err));

    // 接收来自服务器的消息
    newConnection.on('broadcastMessage', (user, message) => {
      setMessages([...messages, `${user}: ${message}`]);
    });

    // 清理工作
    return () => {
      if (newConnection) {
        newConnection.off('broadcastMessage');
        newConnection.stop();
      }
    };
  }, [messages]);

  const sendMessage = () => {
    // 发送消息到服务器
    connection.invoke('SendMessage', 'React User', newMessage)
      .catch(err => console.error('Error while sending message:', err));

    setNewMessage('');
  };

  return (
    <div>
      <h1>SignalR Chat</h1>
      <ul>
        {messages.map((msg, index) => (
          <li key={index}>{msg}</li>
        ))}
      </ul>
      <input
        type="text"
        value={newMessage}
        onChange={e => setNewMessage(e.target.value)}
      />
      <button onClick={sendMessage}>Send</button>
    </div>
  );
};

export default MyChatComponent;
